/**
 * Project Name:IDCardScanCaller
 * File Name:PreviewActivity.java
 * Package Name:com.intsig.idcardscancaller
 * Date:2016年3月15日下午2:14:46
 * Copyright (c) 2016, 上海合合信息 All Rights Reserved.
 */

package preview;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.intsig.imageprocess.R;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.bean.Image;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;

import java.util.ArrayList;
import java.util.List;

import ui.LabelsView;
import util.AnimatorUtils;
import util.CameraRecognizeUtil;
import util.HideControl;

import static com.yuyh.library.imgsel.ui.ISListActivity.INTENT_RESULT;

/**
 * 功能：建议客户集成ISCardScanActivity 重写 addCameraUi 和 recognizeCardCallBack 来自定义相机和相关的业务逻辑，如果有必要请自行修改
 * ClassName:PreviewActivity <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2018年1月8日 上午12:14:46 <br/>
 *
 * @author feicen
 */
public class PreviewActivity extends ISCardScanActivity implements View.OnClickListener {

    private static final int IMAGE_PICKER = 0xf111;
    private static final int REQUEST_CAMERA_CODE = 0xf100 ;
    private static final int REQUEST_LIST_CODE = 0xf200;
    ImageView take_photo_id;
    ImageView iv_album_img;//拍照图片
    ImageView iv_album_entrance;//相框小图
    RelativeLayout rl_root;
    RelativeLayout rl_album;
    TextView tv_num;
    int num = 0;

    List<Image> imgList = new ArrayList<>();

    LabelsView labels;//单拍 多拍

    public static final String EXTRA_KEY_RESULT_ERROR_CODE = "EXTRA_KEY_RESULT_ERROR_CODE";
    public static final String EXTRA_KEY_RESULT = "EXTRA_KEY_RESULT";
    public static final String EXTRA_LIST_RESULT = "EXTRA_LIST_RESULT";


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void addCameraUi(RelativeLayout parentView, final Boolean boolRecognize) {
        // TODO Auto-generated method stub
        super.addCameraUi(parentView, boolRecognize);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

        lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        // **********************************添加动态的布局
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.camera, null);
        take_photo_id = (ImageView) view.findViewById(R.id.take_photo_id);
        iv_album_img = view.findViewById(R.id.iv_album_img);
        rl_root = view.findViewById(R.id.rl_root);
        rl_album = view.findViewById(R.id.rl_album);
        tv_num = view.findViewById(R.id.tv_num);
        labels = view.findViewById(R.id.labels);
        iv_album_entrance = view.findViewById(R.id.iv_album_entrance);
        iv_album_entrance.setOnClickListener(this);
        ArrayList<String> btns = new ArrayList<>();
        btns.add("单拍");
        btns.add("多拍");
        setLabels(btns);
        if (isSignle){
            rl_album.setVisibility(View.GONE);
        }else {
            rl_album.setVisibility(View.VISIBLE);
        }

        take_photo_id.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_UP:
                        if (!boolRecognize) {
                            takepictrueCameraTake(isSignle);
                        } else {
                            Log.e("takepictrueCameraTake", "正在预览识别");
                        }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
        parentView.addView(view, lp);
    }

    /**
     * 单选按钮回调
     *
     * @param btns 单选按钮集合
     */
    private void setLabels(ArrayList<String> btns) {
        labels.setLabels(btns);
        labels.setSelects(0);//默认单拍
        labels.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {
                if (position == 0) {
                    isSignle = true;
                    rl_album.setVisibility(View.GONE);
                } else if (position == 1) {
                    isSignle = false;
                    rl_album.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void recognizeCardCallBack(byte[] data) {
        // TODO Auto-generated method stub
        super.recognizeCardCallBack(data);

        //存储到本地然后返回即可
        //数据处理，客户可以根据自己的逻辑自行处理
        new CameraRecognizeUtil(PreviewActivity.this, take_photo_id){
            @Override
            protected void onResult(String result) {
                super.onResult(result);
                imgList.add(new Image(result,num+""));
                //获取本地地址
                Bitmap bitmap = BitmapFactory.decodeFile(result);
                iv_album_img.setImageBitmap(bitmap);

                if (!isSignle){//多拍
                    //展示2秒
                    new HideControl().startHideTimer(iv_album_img,2000);
                    //执行动画
                    AnimatorUtils.doCartAnimator(PreviewActivity.this,iv_album_img,tv_num,rl_root,null);
                    //更新相册最新的图片
                    iv_album_entrance.setImageBitmap(bitmap);
                    //更新小红点
                    num = num+1;
                    tv_num.setText(new StringBuffer().append(num));
                }else {//单拍 - 直接关闭页面进入处理页面
                    setResult(RESULT_OK,new Intent().putExtra(EXTRA_KEY_RESULT,result));
                    finish();
                }
            }
        }.doRecogWork(data);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        //进入相册
        if (id == R.id.iv_album_entrance){//进入相册
/*            Intent intent = new Intent(this, PhotoAlbumAct.class);
            startActivity(intent);*/
            ISNav.getInstance().init(new ImageLoader() {
                @Override
                public void displayImage(Context context, String path, ImageView imageView) {
                    Glide.with(context).load(path).into(imageView);
                }
            });
            // 自由配置选项
            ISListConfig config = new ISListConfig.Builder()
                    // 是否多选, 默认true
                    .multiSelect(true)
                    // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                    .rememberSelected(false)
                    // “确定”按钮背景色
                    .btnBgColor(Color.GRAY)
                    // “确定”按钮文字颜色
                    .btnTextColor(Color.BLUE)
                    // 使用沉浸式状态栏
                    .statusBarColor(Color.parseColor("#3F51B5"))
                    // 返回图标ResId
                    .backResId(R.drawable.ic_back)
                    // 标题
                    .title("请选择图片")
                    // 标题文字颜色
                    .titleColor(Color.WHITE)
                    // TitleBar背景色
                    .titleBgColor(Color.parseColor("#3F51B5"))
                    // 裁剪大小。needCrop为true的时候配置
                    .cropSize(1, 1, 200, 200)
                    .needCrop(false)
                    // 第一个是否显示相机，默认true
                    .needCamera(false)
                    // 最大选择图片数量，默认9
                    .maxNum(9)
                    //设置展示的图片
                    .setImageList(imgList)
                    .build();
                    // 跳转到图片选择器
            ISNav.getInstance().toListActivity(this, config, REQUEST_LIST_CODE);
        }
    }

    /**
     * 选择照片的回调用
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data != null) {
            String path = data.getStringExtra("result"); // 图片地址
            Log.e("PATH",path);
        }

        if (requestCode == REQUEST_LIST_CODE && resultCode == RESULT_OK && data != null) {
            ArrayList<String> pathList = data.getStringArrayListExtra(INTENT_RESULT);
            //将勾选的图片进行循环切片处理
            initPathToAct(pathList);
        }
    }

    private void initPathToAct(ArrayList<String> pathList) {
        Intent intent = new Intent();
        intent.putStringArrayListExtra(EXTRA_LIST_RESULT,pathList);
        setResult(RESULT_OK,intent);
        finish();
    }
}
